package com.projectsexception.festivales;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.OnGestureListener;
import android.widget.ZoomControls;

import com.projectsexception.festivales.maps.view.MoveImageView;
import com.projectsexception.festivales.setup.MapInfo;
import com.projectsexception.festivales.setup.ProjectResources;
import com.projectsexception.festivales.util.CustomLog;

public class TabMapsActivity extends Activity implements OnGestureListener {
    
    private GestureDetector gestureScanner;
    private MoveImageView image;
    private Integer actualImage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_maps);
        
        this.gestureScanner = new GestureDetector(this);
        List<MapInfo> maps = ProjectResources.getInstance(this).getMaps();
        this.actualImage = maps.get(0).getId();
        loadActualImage();
        
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.tab_maps_menu, menu);
        SubMenu subMenu = menu.findItem(R.id.tab_maps_menu_change).getSubMenu();
        for (MapInfo map : ProjectResources.getInstance(this).getMaps()) {
            subMenu.add(R.id.tab_maps_menu_change, map.getId(), 0, map.getName());
            
        }
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.tab_maps_menu_zoom) {            
            View zoom = findViewById(R.id.zoomcontrols);
            int visibility = View.INVISIBLE;
            String text = getString(R.string.tab_maps_menu_show_zoom);
            if (zoom.getVisibility() == visibility) {
                visibility = View.VISIBLE;
                text = getString(R.string.tab_maps_menu_hide_zoom);
            }
            zoom.setVisibility(visibility);
            item.setTitle(text);
        } else if (item.getGroupId() == R.id.tab_maps_menu_change) {
            if (actualImage != item.getItemId()) {
                actualImage = item.getItemId(); 
                loadActualImage();
            }            
        }
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent me) {
        return gestureScanner.onTouchEvent(me);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        this.image.handleScroll(distanceX, distanceY);
        return true;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {
    }

    @Override
    public void onShowPress(MotionEvent e) {
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return true;
    }
    
    private void loadActualImage() {
        ViewGroup layout = (ViewGroup) findViewById(R.id.map);
        layout.removeAllViews();
        MapInfo mapInfo = getActualMapInfo();
        if (mapInfo != null) {
            byte[] array;
            try {
                // FIXME - Solución temporal
                array = downloadImageFromURL(mapInfo.getImageURL());
                this.image = new MoveImageView(this, BitmapFactory.decodeByteArray(array, 0, array.length));
                layout.addView(image);
            } catch (IOException e) {
                CustomLog.error("TabMapsActivity", e.getMessage());
            }
            
            ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
            zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            image.zoomIn();
                    }
            });
            zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            image.zoomOut();
                    }
            });
        }
    }
    
    private MapInfo getActualMapInfo() {
        MapInfo mapInfo;
        for (Iterator<MapInfo> it = ProjectResources.getInstance(this).getMaps().iterator(); it.hasNext();) {
            mapInfo = it.next();
            if (mapInfo.getId() == actualImage) {
                return mapInfo;
            }
        }
        return null;
    }
    
    private byte[] downloadImageFromURL(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // determine the image size and allocate a buffer
        int fileSize = connection.getContentLength();
        byte[] imageData = new byte[fileSize];

        // download the file
        CustomLog.debug("ImageCache", "fetching image: " + urlString + " (" + fileSize + ")");
        BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());
        int bytesRead = 0;
        int offset = 0;
        while (bytesRead != -1 && offset < fileSize) {
            bytesRead = istream.read(imageData, offset, fileSize - offset);
            offset += bytesRead;
        }

        // clean up
        istream.close();
        connection.disconnect();

        return imageData;
    }
}
